import { useCartStore } from '@/stores/cart'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { RequestCart } from '@/api/cart'
import { ref, type Ref,onMounted } from 'vue'
import type { ICart } from '@/types/types'
import { userStore } from '@/stores/user'


export const useCart = () => {
    const userCount = userStore()
    const cartStore = useCartStore()
    const router = useRouter()
    const goodsList:Ref<Array<ICart>>=ref([])

    // 购物车
    const getCart = async (userId:number)=>{
        const data = await RequestCart(userId)
        const { resultCode, resultInfo } = data
        // console.log(resultInfo)
        if (resultCode === 1) {
            goodsList.value = resultInfo
            cartStore.saveGoodsList(goodsList.value)
        }
    }

    

    // 删除订单
    const bindDelete = (id: number) => {
        cartStore.deleteGoods(id)
        Toast.success('删除成功！')
    }

    // 确认订单
    const bindPayOder = () => {
        router.push({ path: '/onAdd' })
    }

    onMounted(()=>{
        let id = userCount.getCount.uid
        getCart(id)
    })
    return { cartStore, bindDelete, bindPayOder,goodsList }
}
